/*
package org.example.aaaatest.a1;

import com.alibaba.apm.local.aop.ThreadFactoryBuilder;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

*/
/**
 * @description:
 * @author: wangbaogui
 * @create: 2025/5/20 14:17
 **//*

public class A3 {
    public static void main(String[] args) {

    }

    public Result<OrderListResponseDTO> getDetailedOrderInfoAsync(AmapCustomerOrderRequestDTO request) {
        // 初始化线程池（实际使用时应该用Bean管理）
        ExecutorService asyncExecutor = Executors.newFixedThreadPool(
                Runtime.getRuntime().availableProcessors() * 2,
                new ThreadFactoryBuilder().setNameFormat("order-query-%d").build()
        );

        try {
            // 第一阶段：同步获取首页数据
            OrderListRequestDTO baseRequest = buildBaseRequest(request);
            ResponseVO<OrderListResponseDTO> firstPageResponse = fetchFirstPage(baseRequest);

            if (!isValidResponse(firstPageResponse)) {
                return Result.success(emptyResponse());
            }

            OrderListResponseDTO firstPageData = firstPageResponse.getData();
            int totalPages = calculateTotalPages(firstPageData.getPageVO());

            // 如果只有1页直接返回
            if (totalPages == 1) {
                return Result.success(filterAndRebuildResponse(firstPageData));
            }

            // 第二阶段：异步获取剩余页
            List<CompletableFuture<ResponseVO<OrderListResponseDTO>>> futures = new ArrayList<>();
            for (int page = 2; page <= totalPages; page++) {
                final int currentPage = page;
                futures.add(CompletableFuture.supplyAsync(
                        () -> fetchPage(createPageRequest(baseRequest, currentPage)),
                        asyncExecutor
                ));
            }

            // 合并结果
            List<OrderDetailResponseDTO> finalResults = new CopyOnWriteArrayList<>(
                    filterOrders(firstPageData.getList())
            );

            CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
                    .thenApply(v -> futures.stream()
                            .map(CompletableFuture::join)
                            .collect(Collectors.toList()))
                    .thenAccept(responses -> {
                        responses.forEach(response -> {
                            if (isValidResponse(response)) {
                                finalResults.addAll(filterOrders(response.getData().getList()));
                            }
                        });
                    }).get(); // 阻塞等待所有异步任务完成

            return Result.success(buildFinalResponse(finalResults));

        } catch (Exception e) {
            log.error("Async query failed", e);
            return Result.error("查询失败，请稍后重试");
        } finally {
            asyncExecutor.shutdown();
        }
    }

    //------------------------- 工具方法 -------------------------
    private OrderListRequestDTO buildBaseRequest(AmapCustomerOrderRequestDTO request) {
        return OrderListRequestDTO.builder()
                .source("xp")
                .identitys(Collections.singletonList("all"))
                .listQueryCondition(ListQueryCondition.builder()
                        .orderVO(buildOrderVO(request))
                        .pageVO(PageVO.builder().pageNo(1).pageSize(20).build())
                        .build())
                .build();
    }

    private ResponseVO<OrderListResponseDTO> fetchFirstPage(OrderListRequestDTO request) {
        log.info("Fetching first page");
        return rPlatformOrderQueryService.list(request);
    }

    private OrderListRequestDTO createPageRequest(OrderListRequestDTO baseRequest, int page) {
        // 深拷贝避免并发修改问题
        OrderListRequestDTO newRequest = SerializationUtils.clone(baseRequest);
        newRequest.getListQueryCondition().getPageVO().setPageNo(page);
        return newRequest;
    }

    private int calculateTotalPages(PageVO pageVO) {
        if (pageVO == null || pageVO.getTotal() == 0) return 0;
        return (int) Math.ceil((double) pageVO.getTotal() / pageVO.getPageSize());
    }

    private List<OrderDetailResponseDTO> filterOrders(List<OrderDetailResponseDTO> orders) {
        final Set<Integer> EXCLUDED_BIZ_TYPES = Set.of(
                1, 2, 3, 8, 9, 50, 17, 10, 30, 27, 36, 38, 67);

        return orders.stream()
                .filter(order -> !EXCLUDED_BIZ_TYPES.contains(order.getOrder().getBizType()))
                .collect(Collectors.toList());
    }

    private OrderListResponseDTO buildFinalResponse(List<OrderDetailResponseDTO> orders) {
        return OrderListResponseDTO.builder()
                .list(orders)
                .pageVO(PageVO.builder()
                        .pageNo(1)
                        .pageSize(orders.size())
                        .total((long) orders.size())
                        .build())
                .build();
    }

    private boolean isValidResponse(ResponseVO<?> response) {
        return response != null
                && "1".equals(response.getCode())
                && response.getData() != null;
    }

    //------------------------- 异常处理增强 -------------------------
    private ResponseVO<OrderListResponseDTO> fetchPage(OrderListRequestDTO request) {
        try {
            ResponseVO<OrderListResponseDTO> response = rPlatformOrderQueryService.list(request);
            log.debug("Page {} response: {}", request.getPageNo(), toLogStr(response));
            return response;
        } catch (Exception e) {
            log.warn("Page {} request failed", request.getPageNo(), e);
            return fallbackPageResponse();
        }
    }

    private ResponseVO<OrderListResponseDTO> fallbackPageResponse() {
        return ResponseVO.<OrderListResponseDTO>builder()
                .code("500")
                .message("Partial failure")
                .build();
    }
}
*/
